/**
 *
 * @author ilya portnyagin iportnyagin@gmail.com
 */

package ru.portnyagin.helpdeskru.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import ru.portnyagin.helpdeskru.model.ServiceObject;
import ru.portnyagin.helpdeskru.service.ServiceObjectService;
import ru.portnyagin.helpdeskru.util.EJB;

    
    
@FacesConverter(forClass = ServiceObject.class)
public class ServiceObjectConverter implements Converter {
    
    private ServiceObjectService serviceObjectService = EJB.lookup(ServiceObjectService.class);
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || value.length() == 0){ 
            return null;
        }

        ServiceObject technika = serviceObjectService.find(Long.valueOf(value));

        if (technika == null) {
            throw new ConverterException(new FacesMessage("Unknown ServiceObject ID: " + value));
        }

        return technika;
    }
    
    
    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof ServiceObject) || ((ServiceObject) value).getId() == null) {
            return null;
        }

        return String.valueOf(((ServiceObject) value).getId());
    }
    
    
    
    
    
}
